#!/usr/bin/env python
# coding=utf-8

import os.path
from appium import webdriver
import Config


def start_app(install=False):
    app_path = os.path.abspath(os.path.join(os.path.join(__file__, '../..'), 'apps/RapidCalculation-AppleDev.app'))

    desired_caps = {}
    desired_caps['platformName'] = 'iOS'
    desired_caps['platformVersion'] = Config.FISHER_IPHONE_IOSVERSION
    desired_caps['bundleId'] = 'com.appKnowin.RapidCalculation'
    desired_caps['deviceName'] = Config.FISHER_IPHONE_DEVICE_NAME
    desired_caps['udid'] = Config.FISHER_IPHONE_UDID

    if install: desired_caps['app'] = app_path

    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

    _wrap_driver_find_element_functions(driver)
    _wrap_driver_find_element_functions(webdriver.WebElement)
    driver.tap_point = lambda x, y: driver.tap([(x, y)])

    return driver

def _wrap_driver_find_element_functions(driver):
    driver.find_element_by_id = _find_element_wrapper(driver.find_element_by_id)
    driver.find_element_by_xpath = _find_element_wrapper(driver.find_element_by_xpath)
    driver.find_element_by_link_text = _find_element_wrapper(driver.find_element_by_link_text)
    driver.find_element_by_partial_link_text = _find_element_wrapper(driver.find_element_by_partial_link_text)
    driver.find_element_by_name = _find_element_wrapper(driver.find_element_by_name)
    driver.find_element_by_tag_name = _find_element_wrapper(driver.find_element_by_tag_name)
    driver.find_element_by_class_name = _find_element_wrapper(driver.find_element_by_class_name)
    driver.find_element_by_css_selector = _find_element_wrapper(driver.find_element_by_css_selector)
    driver.find_element_by_ios_predicate = _find_element_wrapper(driver.find_element_by_ios_predicate)


def _find_element_wrapper(func):
    from selenium.common.exceptions import NoSuchElementException
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except NoSuchElementException:
            return None
    return wrapper
